package com.qc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qc.dto.Result;
import com.qc.enity.Goods;
import com.qc.enity.Login;
import com.qc.exception.ResultCodeEnum;
import com.qc.service.EmailService;
import com.qc.service.ILoginService;
import com.qc.utils.JwtUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.ibatis.annotations.Param;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.qc.utils.JwtUtils;
@RestController
@RequestMapping("Login")
@CrossOrigin
public class LoginController {
    @Autowired
    private ILoginService loginService ;


    @GetMapping("user/{username}/{password}")
    public  Result<Login> Login(@PathVariable String username, @PathVariable String password){
        System.out.println(username);
        Login login = loginService.loginUser(username, password);

        Map<String, Object> data = new HashMap<>();
        data.put("username", username);
        data.put("password", password);
        String jwt = JwtUtils.generateToken(data);
        System.out.println(jwt);
        login.setUserToken(jwt);
        if (login != null) {
          return Result.successResult(login);
        }
        else return  Result.error(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg());
    }
    // 示例：验证 JWT 的接口
    @GetMapping("verifyToken/{token}")
    public boolean verifyToken(@PathVariable String token) {
        return!JwtUtils.isTokenExpired(token);
    }
//    @Test
//    public void testCreateJwt(){
//        Map<String, Object> data = new HashMap<>();
//        data.put("name","tom");
//        data.put("loginPassword",1234);
//        String jwt = Jwts.builder()
//                .signWith(SignatureAlgorithm.HS256, "wshimiyao")  //ALGORITHM + 密钥
//                .setClaims(data)
//                .setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000))  //有效期，1小时后失效
//                .compact();
//        System.out.println(jwt);
//    }

//    //解析jwt
//    @Test
//    public void testParseJwt(){
//        Claims claims = Jwts.parser()
//                .setSigningKey("wshimiyao")
//                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoidG9tIiwibG9naW5QYXNzd29yZCI6MTIzNCwiZXhwIjoxNjc5MzkwNzEyfQ.KPD0jixzmuP6_UB2T-uIdg8xGfDdnn-QSRSg8_V2waE")
//                .getBody();
//        System.out.println(claims);
//    }

    @GetMapping("user/register/{username}/{password}/{Bid}")
    public  Result<Integer> Register(@PathVariable String username, @PathVariable String password , @PathVariable String Bid ){
        int login = loginService.register(username, password,Bid);
        if (login != 0) {
            return Result.successResult(1);
        }
        else return  Result.error(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg());
    }
    @GetMapping("user/update/{username}/{prePassword}/{password}")
    public  Result<Integer> update(@PathVariable String username, @PathVariable String prePassword , @PathVariable String password ){
        System.out.println(111);
        int login = loginService.update(username, prePassword,password);
        System.out.println(login);
        if (login != 0) {
            return Result.successResult(1);
        }
        else return  Result.error(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg());
    }

    @GetMapping("user/{userBid}")
    public  Result<Integer> selectFamilyByUserBid(@PathVariable String userBid){
        List<Login> list = loginService.selectFamilyByUserBid(userBid);
        System.out.println(list);
        if (list != null) {
            return Result.successResult(list);
        }
        else return  Result.error(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg());
    }
    @PostMapping("user/selectFamilyByParams")
    public  Result<Integer> selectFamilyByParams(@RequestBody Login login){
        List<Login> list = loginService.selectFamilyByParams(login);
        System.out.println(list);
        if (list != null) {
            return Result.successResult(list);
        }
        else return  Result.error(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg());
    }

    /**
     * 发送验证码邮件，并将之存入session
     *
     * @param mail    接受者邮箱
     * @param session 建立session所需
     */
    @Autowired
    private EmailService emailService;

    @GetMapping("/sendEmail")
    public String sendEmail(@RequestParam String to) {
        return emailService.sendVerificationCodeEmail(to);
    }
}
